package net.zjitc.securityloginapijwt.handler;

import cn.hutool.json.JSONUtil;
import cn.hutool.jwt.JWTUtil;
import jakarta.annotation.Resource;
import jakarta.servlet.ServletException;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import net.zjitc.securityloginapijwt.pojo.TUser;
import net.zjitc.securityloginapijwt.result.R;
import net.zjitc.securityloginapijwt.utils.ConstantUtil;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.security.core.Authentication;
import org.springframework.security.web.authentication.AuthenticationSuccessHandler;
import org.springframework.stereotype.Component;

import java.io.IOException;
import java.util.Map;

/**
 * @author 罗翼侨
 * @date 2025/3/10 15:43
 */
@Component
public class MyAuthenticationSuccessHandler implements AuthenticationSuccessHandler {
    @Resource
    private RedisTemplate<String,Object> redisTemplate;

    @Override
    public void onAuthenticationSuccess(HttpServletRequest request, HttpServletResponse response, Authentication authentication) throws IOException, ServletException {
        response.setContentType("application/json");
        response.setCharacterEncoding("utf-8");
        //生成jwt
        TUser tUser = (TUser) authentication.getPrincipal();
        String userJSON = JSONUtil.toJsonStr(tUser);
        String token = JWTUtil.createToken(Map.of("user", userJSON), ConstantUtil.JWT_SECRET.getBytes());
        //设置token到redis中
        redisTemplate.opsForHash().put(ConstantUtil.REDIS_TOKEN_KEY, String.valueOf(tUser.getId()), token);
//采用构建器模式，链式编程创建一个R对象
        R result = R.builder().code(200).msg("登录成功").data(token).build();

//hutool工具包，把R对象转成json字符串
        String json = JSONUtil.toJsonStr(result);

//把json写出去，写出到浏览器客户端
        response.getWriter().write(json);
    }
}
